package org.scmpatrol.core.scm;

import java.util.List;

import javax.ejb.*;

import org.apache.log4j.Logger;
import org.scmpatrol.persistence.SCM;
import org.scmpatrol.scm.SCMCommit;
import org.scmpatrol.scm.SCMRepository;
import org.scmpatrol.scm.common.exception.SCMPatrolException;
import org.scmpatrol.scm.connector.SCMProperties;
import org.scmpatrol.scm.connector.svn.SVNConnector;

@Stateless
@Local(value = SCMRepositoryManager.class)
public class SCMRepositoryManagerBean implements SCMRepositoryManager {
	private final static Logger LOGGER = Logger
			.getLogger(SCMRepositoryManagerBean.class);

	private SCM scm;

	/* (non-Javadoc)
	 * @see org.scmpatrol.core.scm.SCMRepositoryManager#updateRepository(org.scmpatrol.scm.SCMRepository)
	 */
    @TransactionAttribute(TransactionAttributeType.NEVER)
	public void updateRepository(SCMRepository repository) throws SCMPatrolException {

		// TODO hide this in a scm plugin handler
		SVNConnector connector = new SVNConnector();
		SCMProperties properties = new SCMProperties();
		properties.setUrl(repository.getUrl());
		properties.setUser(repository.getUsername());
		properties.setPassword(repository.getUsername());
		try {
			connector.init(properties);
		} catch (SCMPatrolException e) {
			LOGGER.error("Unable to initialize scm connection : " + e.getMessage());
			throw e;
		}
		String lastSCMRevision = connector.getLastRevisionId();
		
		// TODO add limitations on max number of commits retrieved in one request
        while(true) {
            // Looking for the scm-patrol last revision for this repository
            String lastImportedRevision = scm.getLastScmRevisionId(repository.getId());
            String toImport = null;

            if(lastImportedRevision != null) {
                // if lastImportedRevision is null, no revision was imported
                List<SCMCommit> imports = connector.getCommits(lastImportedRevision, 10);
                if(imports.size() > 1) {
                    toImport = imports.get(1).getScmRevision();
                } else {
                    LOGGER.info("Nothing to import for repository " + repository);
                    return;
                }
            } 

            // TODO add a plugin pointcut to deal with revision orders
            LOGGER.info("SCMPatrol revision : " + lastImportedRevision + " start import from " + toImport + " SCM Revision : " + lastSCMRevision);

            List<SCMCommit> commits = connector.getCommits(toImport, 1);

            for (SCMCommit commit : commits) {
                commit.setRepositoryId(repository.getId());
                scm.saveCommit(commit);
                LOGGER.info("Saved commit [" + commit.getId() + ", " + commit.getScmRevision()
                        + ", " + commit.getAuthor() + ", "+ commit.getMessage() + "]");
            }
        }
	}

	@EJB(beanName = "SCMBean")
	void setScm(SCM scm) {
		this.scm = scm;
	}
}
